import {compose, withState} from 'recompose'

const FileSelecter = props => {
    const {title, images, width, height, radius, state: {hover}, setState, onChange, ...restProps} = props;

    const replace = () => {
        const input = document.getElementById('fileInput');
        input.value = ''
    }

    const style = {
        width: width,
        height: height,
        borderRadius: radius,
        background: hover && 'rgba(0, 0, 0, 0.3)'
    };

    const stylePosition = {
        ...style,
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
    }

    return (
        <div width={width} height={height} radius={radius} style={style}
             onMouseOver={() => setState({hover: true})}
             onMouseLeave={() => setState({hover: false})}
        >
            {
                hover &&
                <span style={stylePosition}>{((images || []).length > 0 ? '更换图片' : title) || '选择上传'}</span>
            }

            {
                (images || []).map(x => <img src={x.url} style={style}/>)
            }

            <input id='fileInput' type="file"
                   onChange={(value) => {
                       onChange(value);
                       replace();
                   }} {...restProps}
            />

            <style jsx>{`
                div{
                    position: relative;
                    background: #e8e6e6;
                }

                span{
                    display: inline-block;
                    text-align:center;
                    line-height: ${height};
                    color: #fff;
                }

                img{
                    border:1px solid #ece8e8;
                    z-index:10;
                }

                input{
                    width: 100%;
                    height: 100%;
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    opacity: 0;
                }
            `}</style>
        </div>
    )
}

export default compose(
    withState('state', 'setState', {
        hover: false
    })
)(FileSelecter)
